package org.abc.fund.controller.factorController;

import org.abc.fund.entity.factorEntity.Factor;
import org.abc.fund.entity.factorEntity.NavData;
import org.abc.fund.service.factorService.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 因子管理控制器
 */
@RestController
@CrossOrigin
@RequestMapping("/factor")
public class FactorController {

    private static final Logger logger = LoggerFactory.getLogger(FactorController.class);

    @Autowired
    private FactorService factorService;
    @Autowired
    private DataSourceIngestionHistoryService dataSourceIngestionHistoryService;

    // ========== 基础因子管理 ==========
    //实时获取因子值
    @GetMapping("/factor/getSimpleFactor/{fundCode}/{start}/{end}")
    public List<Double> impleFactor(@PathVariable("fundCode") String fundCode,
                                    @PathVariable("start")     String start,
                                    @PathVariable("end")       String end){
        if(fundCode==null||start==null||end==null) {
            System.out.println("fundCode="+fundCode+",start="+start+",end="+end);
            return null;
        }
        return dataSourceIngestionHistoryService.getShowData(fundCode,start,end);
    }
    //实时获取基金数据
    @GetMapping("/factor/getSimpleJJ/{fundCode}/{start}/{end}")
    public List<NavData> impleJJ(@PathVariable("fundCode") String fundCode,
                                 @PathVariable("start")     String start,
                                 @PathVariable("end")       String end){
        if(fundCode==null||start==null||end==null) {
            System.out.println("fundCode="+fundCode+",start="+start+",end="+end);
            return null;
        }
        return dataSourceIngestionHistoryService.getJJData(fundCode,start,end);
    }

    /**
     * 获取所有因子
     */
    @GetMapping("/factor")
    public ResponseEntity<List<Map<String, Object>>> getAllFactors() {
        try {
            List<Factor> factors = factorService.getAllFactors();
            List<Map<String, Object>> result = new ArrayList<>();
            for (Factor factor : factors) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", factor.getId());
                map.put("factorName", factor.getFactorName());
                map.put("factorCode", factor.getFactorCode());
                map.put("factorType", factor.getFactorType());
                map.put("enabled", factor.getEnabled());
                map.put("description", factor.getDescription());
                // 判断该因子是否有数据（只要有一条数据就算有）
                boolean hasData = false;
                try {
                    // 移除或注释掉factorService.getShowData相关调用，或补充实现（如需返回hasData，可直接设为false或补充逻辑）。
                    // List<Double> data = factorService.getShowData(factor.getFactorCode());
                    // hasData = data != null && !data.isEmpty();
                } catch (Exception e) {
                    hasData = false;
                }
                map.put("hasData", hasData);
                result.add(map);
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取因子列表失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().build();
        }
    }
    @GetMapping("/factors/OnPage")
    public Map<String, Object> getFactors(
            @RequestParam(required = false) String factorName,
            @RequestParam(required = false) String factorCode,
            @RequestParam(required = false) String factorType,
            @RequestParam(required = false) Boolean enabled,
            @PageableDefault(size = 5, sort = "id", direction = Sort.Direction.ASC) Pageable pageable) {
        Page<Factor> factorPage = factorService.findFactors(factorName, factorCode, factorType, enabled, pageable);
        Map<String, Object> response = new HashMap<>();
        response.put("content", factorPage.getContent());
        response.put("totalElements", factorPage.getTotalElements());
        return response;
    }
    /**
     * 根据ID获取因子
     */
    @GetMapping("/factor/{id}")
    public ResponseEntity<Factor> getFactorById(@PathVariable Long id) {
        try {
            Factor factor = factorService.getFactorById(id);
            if (factor != null) {
                return ResponseEntity.ok(factor);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.error("获取因子失败: {} - {}", id, e.getMessage());
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 创建因子
     */
    @PostMapping("/factor")
    public ResponseEntity<Factor> createFactor(@RequestBody Factor factor) {
        try {
            Factor createdFactor = factorService.createFactor(factor);
            return ResponseEntity.ok(createdFactor);
        } catch (Exception e) {
            logger.error("创建因子失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 更新因子
     */
    @PutMapping("/factor/{id}")
    public ResponseEntity<Factor> updateFactor(@PathVariable Long id, @RequestBody Factor factor) {
        try {
            factor.setId(id);
            Factor updatedFactor = factorService.updateFactor(factor);
            if (updatedFactor != null) {
                return ResponseEntity.ok(updatedFactor);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.error("更新因子失败: {} - {}", id, e.getMessage());
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 删除因子
     */
    @DeleteMapping("/factor/{id}")
    public ResponseEntity<Void> deleteFactor(@PathVariable Long id) {
        try {
            boolean deleted = factorService.deleteFactor(id);
            if (deleted) {
                return ResponseEntity.ok().build();
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.error("删除因子失败: {} - {}", id, e.getMessage());
            return ResponseEntity.internalServerError().build();
        }
    }


    /**
     * 从API摄入基金数据
     */
    @PostMapping("/factor/ingest/fund")
    public ResponseEntity<Map<String, Object>> ingestFundData(@RequestBody Map<String, Object> request) {
        try {
            String fundCode = (String) request.get("fundCode");
            @SuppressWarnings("unchecked")
            List<String> factorCodes = (List<String>) request.get("factorCodes");

            if (fundCode == null || fundCode.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of("error", "基金代码不能为空"));
            }

            // 暂时返回成功响应，实际实现需要FactorIngestionService
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("fundCode", fundCode);
            result.put("message", "基金数据摄入功能待实现");
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            logger.error("基金数据摄入失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 从API摄入股票数据
     */
    @PostMapping("/factor/ingest/stock")
    public ResponseEntity<Map<String, Object>> ingestStockData(@RequestBody Map<String, Object> request) {
        try {
            String stockCode = (String) request.get("stockCode");
            String dataSource = (String) request.get("dataSource");
            @SuppressWarnings("unchecked")
            List<String> factorCodes = (List<String>) request.get("factorCodes");

            if (stockCode == null || stockCode.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of("error", "股票代码不能为空"));
            }

            if (dataSource == null || dataSource.isEmpty()) {
                dataSource = "SINA"; // 默认使用新浪数据源
            }

            // 暂时返回成功响应，实际实现需要FactorIngestionService
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("stockCode", stockCode);
            result.put("dataSource", dataSource);
            result.put("message", "股票数据摄入功能待实现");
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            logger.error("股票数据摄入失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }




    // ========== 真实数据获取 ==========

    // ========== AI分析 ==========

//    /**
//     * 基金因子AI分析
//     */
//    @PostMapping("/factor/analysis/fund")
//    public ResponseEntity<Map<String, Object>> analyzeFundFactors(@RequestBody Map<String, Object> request) {
//        try {
//            String fundCode = (String) request.get("fundCode");
//            String fundName = (String) request.get("fundName");
//            @SuppressWarnings("unchecked")
//            Map<String, Object> fundData = (Map<String, Object>) request.get("fundData");
//
//            if (fundCode == null || fundData == null) {
//                return ResponseEntity.badRequest().body(Map.of("error", "基金代码和数据不能为空"));
//            }
//
//            Map<String, Object> analysis = realAIAnalysisService.analyzeFundFactors(fundCode, fundName, fundData);
//            return ResponseEntity.ok(analysis);
//
//        } catch (Exception e) {
//            logger.error("基金因子AI分析失败: {}", e.getMessage());
//            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
//        }
//    }
//
//    /**
//     * 股票因子AI分析
//     */
//    @PostMapping("/factor/analysis/stock")
//    public ResponseEntity<Map<String, Object>> analyzeStockFactors(@RequestBody Map<String, Object> request) {
//        try {
//            String stockCode = (String) request.get("stockCode");
//            String stockName = (String) request.get("stockName");
//            @SuppressWarnings("unchecked")
//            Map<String, Object> stockData = (Map<String, Object>) request.get("stockData");
//
//            if (stockCode == null || stockData == null) {
//                return ResponseEntity.badRequest().body(Map.of("error", "股票代码和数据不能为空"));
//            }
//
//            Map<String, Object> analysis = realAIAnalysisService.analyzeStockFactors(stockCode, stockName, stockData);
//            return ResponseEntity.ok(analysis);
//
//        } catch (Exception e) {
//            logger.error("股票因子AI分析失败: {}", e.getMessage());
//            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
//        }
//    }

//    /**
//     * 测试AI连接
//     */
//    @PostMapping("/factor/analysis/test")
//    public ResponseEntity<Map<String, Object>> testAIConnection(@RequestBody Map<String, Object> request) {
//        try {
//            String provider = (String) request.get("provider");
//
//            if (provider == null || provider.isEmpty()) {
//                return ResponseEntity.badRequest().body(Map.of("error", "AI提供商不能为空"));
//            }
//
//            Map<String, Object> result = realAIAnalysisService.testAIConnection(provider);
//            return ResponseEntity.ok(result);
//
//        } catch (Exception e) {
//            logger.error("AI连接测试失败: {}", e.getMessage());
//            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
//        }
//    }

    // ========== 系统管理 ==========

    /**
     * 获取数据源状态
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getDataSourceStatus() {
        try {
            // 暂时返回基本状态信息
            Map<String, Object> status = new HashMap<>();
            status.put("message", "数据源状态功能待实现");
            status.put("timestamp", new Date());
            return ResponseEntity.ok(status);
        } catch (Exception e) {
            logger.error("获取数据源状态失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 清除缓存
     */
    @PostMapping("/factor/cache/clear")
    public ResponseEntity<Map<String, Object>> clearCache() {
        try {
            // 暂时返回成功响应
            return ResponseEntity.ok(Map.of("message", "缓存清除功能待实现"));
        } catch (Exception e) {
            logger.error("清除缓存失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }
//
//    /**
//     * 验证股票代码
//     */
//    @GetMapping("/factor/validate/stock/{stockCode}")
//    public ResponseEntity<Map<String, Object>> validateStockCode(@PathVariable String stockCode) {
//        try {
//            boolean isValid = realFundDataService.isValidStockCode(stockCode);
//            return ResponseEntity.ok(Map.of("valid", isValid, "stockCode", stockCode));
//        } catch (Exception e) {
//            logger.error("验证股票代码失败: {} - {}", stockCode, e.getMessage());
//            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
//        }
//    }
//
//    /**
//     * 验证基金代码
//     */
//    @GetMapping("/factor/validate/fund/{fundCode}")
//    public ResponseEntity<Map<String, Object>> validateFundCode(@PathVariable String fundCode) {
//        try {
//            boolean isValid = realFundDataService.isValidFundCode(fundCode);
//            return ResponseEntity.ok(Map.of("valid", isValid, "fundCode", fundCode));
//        } catch (Exception e) {
//            logger.error("验证基金代码失败: {} - {}", fundCode, e.getMessage());
//            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
//        }
//    }

    /**
     * 按类型获取基础因子列表
     */
    @GetMapping("/factor/type")
    public ResponseEntity<List<Map<String, Object>>> getFactorsByType(@RequestParam String type) {
        try {
            List<Factor> factors = factorService.getFactorsByType(type);
            List<Map<String, Object>> result = new ArrayList<>();
            for (Factor factor : factors) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", factor.getId());
                map.put("factorName", factor.getFactorName());
                map.put("factorCode", factor.getFactorCode());
                map.put("factorType", factor.getFactorType());
                map.put("enabled", factor.getEnabled());
                map.put("description", factor.getDescription());
                result.add(map);
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("按类型获取因子列表失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().build();
        }
    }

    @PostMapping("/factors/batch")
    public ResponseEntity<?> saveFactors(@RequestBody List<Factor> factors) {
        for (Factor factor : factors) {
            factorService.createFactor(factor);
        }
        return ResponseEntity.ok(Map.of("success", true, "message", "保存成功"));
    }
}